package my.http;

import android.util.Log;

import com.ffapp.demo.basis.Constants;
import com.ffapp.demo.bean.LoginBean;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
 
/**
 * 自动刷新token的拦截器
 * 
 * @author shijiacheng
 * @version 1.0
 */
 
public class TokenInterceptor implements Interceptor {
 
  private static final String TAG = "HTTP";
 
  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Response response = chain.proceed(request);
//    Log.d(TAG, "response.code=" + response.code());
 
    //根据和服务端的约定判断token过期
    if (LoginBean.isLogin() && isTokenExpired(response)) {
//    if (LoginBean.isLogin() ) {
      HttpUrl url = request.url();
      Log.d(TAG, url.toString()+"自动刷新Token,然后重新请求数据");
      //同步请求方式，获取最新的Token
      String newToken = getNewToken();
//      LogUtil.i(TAG,"newToken-------->"+newToken);
      //使用新的Token，创建新的请求
      Request.Builder builder = request
              .newBuilder();
      MyHttpUtils.AddHeaderToBuilder(builder,null,false);
      Request newRequest =builder.build();
      response.close(); // 很简单，加上这一句
      //重新请求
      return chain.proceed(newRequest);
    }
    return response;
  }
 
  /**
   * 根据Response，判断Token是否失效
   *
   * @param response
   * @return
   */
  private boolean isTokenExpired(Response response) {
//    LogUtil.i(MyHttpUtils.tag,"isTokenExpired--->"+response.code());

    if (response.code() == 401 || response.code() == 403) {
      return true;
    }
    return false;
  }
 
  /**
   * 同步请求方式，获取最新的Token
   *
   * @return
   */
  private String getNewToken() throws IOException {
    // 通过获取token的接口，同步请求接口
    String newToken = "";
    MyParams params = new MyParams();
    params.put("refreshToken", LoginBean.getRefreshToken());
//        showProgress();
    MyHttpUtils.postExcute(Constants.URL_USER_REFRESH_TOKEN, params, new MyHttpListener() {
      @Override
      public void onSuccess(int httpWhat, Object result) {
//                BasisBean basisBean = (BasisBean) result;
        LoginBean loginBean = (LoginBean) result;
        LoginBean loginBeanCache = LoginBean.getFromCache();
        loginBeanCache.setAccess_token(loginBean.getAccess_token());
        loginBeanCache.setExpires_in(loginBean.getExpires_in());
        loginBeanCache.setScope(loginBean.getScope());
        loginBeanCache.setToken_type(loginBean.getToken_type());
        loginBeanCache.setJti(loginBean.getJti());
        loginBeanCache.save();
      }

      @Override
      public void onFailure(int httpWhat, Object result) {
//                super.onFailure(httpWhat, result);
//        LoginBean.logout();
        LoginBean loginBeanCache = LoginBean.getFromCache();
        loginBeanCache.setAccess_token("");
        loginBeanCache.save();
      }

      @Override
      public boolean onHttpFailure(int httpWhat, Throwable arg3) {
//        return super.onHttpFailure(httpWhat, arg3);
        return true;
      }

      @Override
      public void onFinish(int httpWhat) {
//                dismissProgress();
      }
    }, 0, LoginBean.class);

    return LoginBean.getUserToken();
  }
}